package cc.rssoft.qqd.sdk;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

import cc.rssoft.qqd.sdk.command.GetCustomerContactHistoryCommand;
import cc.rssoft.qqd.sdk.command.internal.AbstractQqdApiCommand;
import cc.rssoft.qqd.sdk.command.internal.AbstractQqdApiResponse;
import cc.rssoft.qqd.sdk.command.response.GetCustomerContactHistoryResponse;
import cc.rssoft.qqd.sdk.util.HttpRequest;
import cc.rssoft.qqd.sdk.util.QqdSignUtil;


public class QqdServer {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private String rsmwUrl;
	private String apiSecret;
	private int connectTimeout = 2000;
	private int readTimeout = 2000;

	public QqdServer(String rsmwUrl, String apiSecret, int connectTimeout, int readTimeout) {
		this.rsmwUrl = rsmwUrl;
		this.apiSecret = apiSecret;
		this.connectTimeout = connectTimeout;
		this.readTimeout = readTimeout;
	}

	private <T extends AbstractQqdApiResponse> T sendCommand(AbstractQqdApiCommand apiCommand, Class<T> clazz) {
		String commandString = apiCommand.toJsonString();
		String url = rsmwUrl + "?sign=" + QqdSignUtil.sign(commandString, apiSecret);
		logger.debug("request url="+url);
		logger.debug("request body="+commandString);
		HttpRequest httpRequest = HttpRequest.post(url).contentType("text/plain;charset=UTF-8")
				.connectTimeout(connectTimeout).readTimeout(readTimeout).send(commandString);
		httpRequest.trustAllCerts();
		String body = httpRequest.body();
		logger.debug("RESPONSE BODY="+body);
		T t = JSON.parseObject(body, clazz);
		
		return t;
	}
	
	public GetCustomerContactHistoryResponse getCustomerContactHistory(String customerPhoneNumber, Date date, Integer limit){
		GetCustomerContactHistoryCommand request = new GetCustomerContactHistoryCommand(customerPhoneNumber, date, limit);
		GetCustomerContactHistoryResponse response = this.sendCommand(request, GetCustomerContactHistoryResponse.class);
		return response;
	}
}
